import * as API_Trade from '../../api/trade'
import regeneratorRuntime from '../../lib/wxPromise.min.js'
import { RegExp, Foundation } from '../../ui-utils/index'
const app = getApp()
let util = require('../../utils/util.js')
const middleware = require('../../utils/middleware.js')

Page({
  data: {
    locationData: {},
    tabList: [
      {
        dataIndex: 0,
        type: 'SHETUAN_CART',
        name: '团购'
      },
      {
        dataIndex: 1,
        type: 'COMMON_CART',
        name: '商城'
      }
    ],
    tabActive: 'SHETUAN_CART',
    commonCart: 0, // 商城购物车数量
    shetuanCart: 0, // 团购购物车数量
    /** 购物车商品列表 */
    shopList: [],
    /** sku列表 */
    skuList: [],
    /* 选中商品数量 */
    checkedCount: 0,
    /* 所有商品数量 */
    allCount: 0,
    /** 购物车总计清单 */
    cartTotal: {},

    /** 当前操作的输入框的值【变化之前】 */
    current_input_value: 1,
    activity_options: [],
    sku_checkout: [],
    promotions_checkout: '',
    cur_sku_id: null,
    /** 是否全选 */
    all_checked: false,
    delBtnWidth: 120,
    finished: false
  },
  // 页面初始化 options为页面跳转所带来的参数
  onLoad() {
    this.initEleWidth();
  },
  onShow() {
    this.setData({
      locationData: app.globalData.locationData
    });
    if (wx.getStorageSync("refresh_token")) {
      this.getCartCount();
      this.getCartList();
    } else {
      this.setData({ shopList: [], finished: true })
    }
  },
  // 切换购物车类型
  switchTab (e) {
    const { type } = e.currentTarget.dataset;
    this.setData({
      tabActive: type
    });
    this.getCartList();
  },
  // 获取购物车统计数量
  getCartCount () {
    let { city } = app.globalData.locationData;
    API_Trade.getCartCount(city).then(res => {
      const { COMMON_CART, SHETUAN_CART } = { ...res };
      let _tabList = this.data.tabList;
      let { tabList } = this.data;
      _tabList[0].cartNum = SHETUAN_CART || 0;
      _tabList[1].cartNum = COMMON_CART || 0;
      this.setData({
        tabList
      });
    }).catch();
  },
  // 获取购物车数据
  async getCartList() {
    const { province, city } = this.data.locationData;
    let _position = city || province;
    const { cart_list, total_price } = await API_Trade.getCarts(this.data.tabActive, 'all', 'CART', _position);
    this.setData({ finished: true });
    let _checkedCount = 0;
    let _allCount = 0;
    let _skuList = [];
    cart_list.forEach(shop => {
      // 拆分总价的整数和小数
      let totalPrice = Foundation.formatPrice(shop.price.total_price);
      shop.price.priceInt = totalPrice.split('.')[0] || '0';
      shop.price.priceFloat = totalPrice.split('.')[1] || '00';
      shop.price.total_price = Foundation.formatPrice(shop.price.total_price)
      // 已选中商品种类
      shop.checkedNum = 0;
      // 默认隐藏超过2件的商品
      shop.showOpen = false;
      let _shopList = this.data.shopList || [];
      for (let _shopItem of _shopList) {
        if (_shopItem.seller_id === shop.seller_id) {
          shop.showOpen = _shopItem.showOpen;
          break;
        };
      };
      // console.log(Math.round(new Date().getTime()/1000));
      shop.sku_list.forEach(item => {
        item.pick_time = Foundation.unixToDate(item.pick_time, 'MM月dd日');
        item.pick_tomorry = item.pick_time_text && (item.pick_time_text).indexOf('明日') > -1;
        item.show_tag = shop.self_operated == 1 ? 1 : shop.is_local == 1 ? 2 : 0;
        if (item.invalid !== 1) _allCount += item.num
        if (item.checked && item.invalid !== 1) _checkedCount += item.num
        item.purchase_price = Foundation.formatPrice(item.purchase_price)
        if (!item.skuName) item.skuName = this.formatterSkuSpec(item)
        if (item.checked === 1) shop.checkedNum += 1;
      });
      _skuList.push(...shop.sku_list);
    })
    // 数据处理
    total_price.total_price = Foundation.formatPrice(total_price.total_price);
    if (total_price.cash_back !== 0) {
      total_price.cash_back = Foundation.formatPrice(total_price.cash_back);
    };
    this.setData({
      shopList: cart_list,
      cartTotal: total_price,
      checkedCount: _checkedCount,
      allCount: _allCount,
      skuList: _skuList
    });
    setTimeout(() => {
      this.setData({ all_checked: this.isCheckedAll() })
    });
  },
  // 判断购物车商品已全选
  isCheckedAll() {
    return !!this.data.checkedCount && this.data.checkedCount === this.data.allCount
  },
  /** 勾选、取消勾选商品 */
  handleCheckSku(e) {
    wx.vibrateShort({});
    const { sku, shop } = e.currentTarget.dataset;
    API_Trade.updateSkuChecked(sku.sku_id, sku.checked ? 0 : 1, shop.cart_source_type).then(_ => {
      setTimeout(_ => {
        this.getCartCount();
        this.getCartList();
      }, 200)
    }).catch()
  },
  /** 勾选、取消勾选店铺 */
  handleCheckShop(e) {
    wx.vibrateShort({});
    const shop = e.currentTarget.dataset.shop;
    API_Trade.checkShop(shop.seller_id, shop.checked ? 0 : 1, shop.cart_source_type).then(_ => {
      setTimeout(_ => {
        this.getCartCount();
        this.getCartList();
      }, 200)
    }).catch()
  },
  /** 规格格式化显示 */
  formatterSkuSpec(sku) {
    if (!sku.spec_list || !sku.spec_list.length) return ''
    return sku.spec_list.map(spec => spec.spec_value).join(' - ')
  },
  /** 全选、取消全选 */
  handleCheckAll() {
    API_Trade.checkAll(this.data.all_checked ? 0 : 1).then(_ => {
      setTimeout(_ => {
        that.getCartCount();
        that.getCartList();
      }, 200);
    }).catch()
  },

  // 显示隐藏商品
  toggleShow(e) {
    let _index = e.currentTarget.dataset.index;
    let { shopList } = this.data;
    shopList[_index].showOpen = !shopList[_index].showOpen;
    this.setData({ shopList });
  },
  /** 更新商品数量 */
  handleUpdateSkuNum(e) {
    const { carttype, sku, symbol } = e.currentTarget.dataset;
    if (!symbol || typeof symbol !== 'string') {
      if (!e.detail.value) {
        wx.showToast({ title: '输入格式有误，请输入正整数', icon: 'none' })
        this.setData({
          shopList: this.data.shopList
        });
        return
      };
      let _num = parseInt(e.detail.value)
      if (isNaN(_num) || _num < 1) {
        wx.showToast({ title: '输入格式有误，请输入正整数', icon: 'none' })
        return
      }
      if (_num >= sku.enable_quantity) {
        wx.showToast({ title: '超过最大库存', icon: 'none' })
        return
      }
      this.updateSkuNum({ sku_id: sku.sku_id, num: _num, cart_source_type: carttype })
    } else {
      wx.vibrateShort({});
      let that = this;
      if (symbol === '-' && sku.num < 2) {
        wx.showModal({
          title: '提示',
          content: '确定要删除此商品吗?',
          confirmColor: '#f42424',
          success(res) {
            /** 删除 */
            if (res.confirm) {
              API_Trade.deleteSkuItem(sku.sku_id, carttype).then(_ => {
                setTimeout(_ => {
                  that.getCartCount();
                  that.getCartList();
                }, 200);
              }).catch(error => {
                console.log(error);
              });
            }
          }
        });
        return;
      };
      if (symbol === '+' && sku.num >= sku.enable_quantity) {
        wx.showToast({ title: '超过最大库存', icon: 'none' })
        return
      }
      let _num = symbol === '+' ? sku.num + 1 : sku.num - 1
      this.updateSkuNum({ sku_id: sku.sku_id, num: _num, cart_source_type: carttype })
    }
  },
  /* 更新sku数据 */
  updateSkuNum(params) {
    setTimeout(() => {
      API_Trade.updateSkuNum(params.sku_id, params.num, params.cart_source_type).then(_ => {
        setTimeout(_ => {
          this.getCartCount();
          this.getCartList();
        }, 200)
      }).catch()
    }, 200)
  },
  /** 删除 */
  handleDelete: util.throttle(function (e) {
    const { sku, carttype } = e.currentTarget.dataset;
    let that = this;
    this.data.shopList.forEach(key => { key.sku_list.forEach(item => { item.txtStyle = '' }) })
    this.setData({ shopList: this.data.shopList })
    wx.showModal({
      title: '提示',
      content: '确定要删除此商品吗?',
      confirmColor: '#f42424',
      success(res) {
        if (res.confirm) {
          API_Trade.deleteSkuItem(sku.sku_id, carttype).then(_ => {
            wx.showToast({ title: '删除成功!' })
            setTimeout(_ => {
              that.getCartCount();
              that.getCartList();
            }, 200)
            that.setData({ current: 0 })
          }).catch()
        }
      }
    })
  }),
  /** 去结算 */
  handleCheckout: util.throttle(function (e) {
    const _shop = e.currentTarget.dataset.shop;
    let _checkedSku = _shop.sku_list.map(item => {
      if (item.checked && item.invalid) {
        return item;
      };
    });
    if (!_checkedSku.length) {
      wx.showToast({
        title: '请选择有效的商品去结算',
        icon: 'none'
      });
      return false
    };
    let _url = _shop.cart_source_type === 'SHETUAN_CART' ? '/pages/shopping/checkout/checkout-group' : '/pages/shopping/checkout/checkout';
    wx.navigateTo({
      url: `${_url}?way=CART&&sellerId=${_shop.seller_id}`
    });
  }),
  // 开始滑动事件
  touchS: function (e) {
    if (e.touches.length == 1) {
      this.setData({
        //设置触摸起始点水平方向位置 
        startX: e.touches[0].clientX
      });
    }
  },
  touchM: function (e) {
    if (e.touches.length == 1) {
      //手指移动时水平方向位置 
      var moveX = e.touches[0].clientX;
      //手指起始点位置与移动期间的差值 
      var disX = this.data.startX - moveX;
      var delBtnWidth = this.data.delBtnWidth;
      var txtStyle = "";
      if (disX == 0 || disX < 0) { //如果移动距离小于等于0，文本层位置不变 
        txtStyle = "left:0px";
      } else if (disX > 0) { //移动距离大于0，文本层left值等于手指移动距离 
        txtStyle = "left:-" + disX + "px";
        if (disX >= delBtnWidth) {
          //控制手指移动距离最大值为删除按钮的宽度 
          txtStyle = "left:-" + delBtnWidth + "px";
          //获取手指触摸的是哪一项 
          var shopIndex = e.currentTarget.dataset.shopindex
          var skuIndex = e.currentTarget.dataset.skuindex
          var list = this.data.shopList;
          list.forEach(key => { key.sku_list.forEach(item => { item.txtStyle = '' }) })
          list[shopIndex].sku_list[skuIndex].txtStyle = txtStyle;
          //更新列表的状态 
          this.setData({ shopList: list })
        }
      }
    }
  },
  // 滑动中事件
  touchE: function (e) {
    if (e.changedTouches.length == 1) {
      //手指移动结束后水平位置 
      var endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离 
      var disX = this.data.startX - endX;
      var delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮 
      var txtStyle = "";
      txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "px" : "left:0px";

      //获取手指触摸的是哪一项 
      var shopIndex = e.currentTarget.dataset.shopindex
      var skuIndex = e.currentTarget.dataset.skuindex
      var list = this.data.shopList;
      list.forEach(key => { key.sku_list.forEach(item => { item.txtStyle = '' }) })
      list[shopIndex].sku_list[skuIndex].txtStyle = txtStyle;
      //更新列表的状态 
      this.setData({ shopList: list })
    }
  },
  //获取元素自适应后的实际宽度 
  getEleWidth: function (w) {
    var real = 0;
    try {
      var res = wx.getSystemInfoSync().windowWidth;
      var scale = (750 / 2) / (w / 2);
      real = Math.floor(res / scale);
      return real;
    } catch (e) {
      return false;
    }
  },
  initEleWidth: function () {
    var delBtnWidth = this.getEleWidth(this.data.delBtnWidth)
    this.setData({ delBtnWidth: delBtnWidth })
  },
  // 去购物
  goshopping() {
    const { tabActive } = this.data;
    if (tabActive === 'SHETUAN_CART') {
      wx.switchTab({ url: '/pages/index-group/index/index' })
    } else {
      wx.switchTab({ url: '/pages/index/index' })
    };
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (wx.getStorageSync("refresh_token")) {
      this.getCartCount();
      this.getCartList();
    } else {
      this.setData({ shopList: [], finished: true })
    }
    // 停止下拉[回弹]
    wx.stopPullDownRefresh();
  }
})